//
//  EMConversationViewCell.swift
//  HyphenateIMDemo
//
//  Created by Shang Hai Rui Xi on 2019/3/8.
//  Copyright © 2019 Shang Hai Rui Xi. All rights reserved.
//

import UIKit

class EMConversationViewCell: ConversationViewCell {
    
    public var conversation: EMConversation? {
        didSet {
            configConversation()
        }
    }

    override func awakeFromNib() {
        super.awakeFromNib()
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
    }
    
    private func configConversation() {
        guard let conversation = conversation else { return }
        
        titleLabel.text = conversation.conversationId
        
        var timeInterval = conversation.latestMessage.timestamp
        if timeInterval > 140000000000 {
            timeInterval = timeInterval / 1000
        }
        let formatter = DateFormatter.init()
        formatter.dateFormat = "YYYY-MM-dd"
        let latestMessageTime = formatter.string(from: Date.init(timeIntervalSince1970: TimeInterval(timeInterval)))
        timeLabel.text = latestMessageTime

        var attributedStr = NSMutableAttributedString.init()
        var latestMessageTitle = ""
        guard let lastMessage = conversation.latestMessage else { return }
        switch lastMessage.body.type {
        case EMMessageBodyTypeImage:
            latestMessageTitle = "图片"
        case EMMessageBodyTypeText:
            let didReceiveText = EaseConvertToCommonEmoticonsHelper.convert(toCommonEmoticons: (lastMessage.body as? EMTextMessageBody)?.text)
            latestMessageTitle = didReceiveText ?? ""
            if lastMessage.ext?[MESSAGE_ATTR_IS_BIG_EXPRESSION] != nil {
                latestMessageTitle = "动画表情"
            }
        case EMMessageBodyTypeVoice:
            latestMessageTitle = "语音"
        case EMMessageBodyTypeLocation:
            latestMessageTitle = "位置"
        case EMMessageBodyTypeVideo:
            latestMessageTitle = "视频"
        case EMMessageBodyTypeFile:
            latestMessageTitle = "文件"
        default:
            break
        }
        attributedStr = NSMutableAttributedString.init(string: latestMessageTitle)
        detailLabel.attributedText = attributedStr
        
        let number = Int(conversation.unreadMessagesCount)
        avatarView.pp.addBadge(number: number)
    }
}
